const express = require("express");
const router = express.Router();
const con = require("../db/mysql")


router.get('/', async (req, res, next) => {
  const { page, limit,subcategory,id } = req.query;
  let where="1 ";
  if(subcategory!=undefined){
    where+=`AND subcategory='${subcategory}'`
  }
  if(id!=undefined){
    where+=`AND id='${id}'`
  }
  try {
    const result = await con.query(`SELECT * FROM goods WHERE ${where} ORDER BY id DESC LIMIT ${limit * 1} OFFSET ${(page - 1) * limit}; SELECT COUNT(*) AS total FROM goods`) 
      res.json({
        msg: "查询成功",
        code: 200,
        data: result[0],
        total: result[1][0].total
      });
   
  } catch (error) {
    console.log(error);

  }

});

router.post('/', async (req, res, next) => {
  const { goods_name, thumb, des, sell_price, show_price, label, banner,
    limi, number, cost, state, store, subcategory, create_time, update_time, is_delete } = req.body;
  try {
    const result = await con.query(`INSERT INTO goods (
    goods_name,thumb,des,sell_price,show_price,label,banner,limi,number,cost,state,
    store,subcategory,create_time,update_time,is_delete
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?);
`, [goods_name, thumb, des, sell_price, show_price, label, banner, limi, number, cost, state,
      store, subcategory, create_time, update_time, is_delete]);
    if (result.affectedRows === 1) {
      res.json({
        msg: "添加成功",
        code: 200
      });
    } else {
      res.json({
        msg: "添加失败",
        code: 500
      });
    }
  } catch (error) {
    console.log(error);
  }
});


router.delete('/:id', async (req, res) => {
  const { id } = req.params;
  try {
    await con.query(`DELETE FROM goods WHERE id=?`, id, (err, result) => {
      if (result.affectedRows === 1) {
        res.json({
          msg: "删除成功",
          code: 200
        });
      } else {
        res.json({
          msg: "删除失败",
          code: 500
        });
      }
    });
  } catch (error) {
    console.log(error);

  }

});

router.put('/:id', async (req, res) => {
  const { id } = req.params;
  const { goods_name, thumb, pid, sort } = req.body;
  try {
    const result2 = await con.query(`UPDATE goods SET goods_name=?,thumb=?,pid=?,sort=?WHERE id=?`, [goods_name, thumb, pid, sort, id]);
    if (result2.affectedRows === 1) {
      res.json({
        msg: "更新成功",
        code: 200
      });
    } else {
      res.json({
        msg: "更新失败",
        code: 500
      });
    }

  } catch (e) {
    console.log(e);
  }

});

module.exports = router;











module.exports = router;